package com.example.a22310.myapplication.Activity;
//红色的R解决不了
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import com.example.a22310.myapplication.Abstractclass.BaseActivity;
import com.example.a22310.myapplication.Beans.UserInfo;
import com.example.a22310.myapplication.Beans.user;
import com.example.a22310.myapplication.Fragment.ChoicenessActivityFragment;
import com.example.a22310.myapplication.Fragment.ClubFragment;
import com.example.a22310.myapplication.Fragment.PostFragment;
import com.example.a22310.myapplication.Fragment.TrainFragment;
import com.example.a22310.myapplication.Listener.ClubListener;
import com.example.a22310.myapplication.Model.UserModel;
import com.example.a22310.myapplication.R;
import com.example.a22310.myapplication.Service.service;
import com.scwang.smartrefresh.header.material.CircleImageView;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.provider.ContactsContract.CommonDataKinds.Website.URL;

public class MainActivity extends BaseActivity

        implements NavigationView.OnNavigationItemSelectedListener,ClubListener<user> {


    private LinearLayout id_tab_train;
    private LinearLayout id_tab_club;
    private LinearLayout id_tab_activity;
    private LinearLayout id_tab_post;

    private ImageButton mImgTrain;
    private ImageButton mImgClub;
    private ImageButton mImgChoicenessActivity;
    private ImageButton mImgPost;

    private TextView tv01;
    private TextView tv02;
    private TextView tv03;
    private TextView tv04;
    private TextView title;
    private TextView username;

    private ViewPager main_viewPager ;
    private FragmentPagerAdapter mAdapter;
    private ArrayList<Fragment> fragmentList;
    private long mExitTime;

    private TextView tv_bubble;
    private ImageView notification,id_addpost_img,alter;
    private CircleImageView Img_user;

    private Intent intent = new Intent();

    private String newsBubbleNumber  ;

    private String FILENAME = "yuejian'data";

    private int userid ;

    private MyBroadCastReciver myBroadCastReciver =null;




    @Override
    public void setContentView() {
        setContentView(R.layout.activity_main);
        userid = getUserid();
        startService();
        registerBroadCast();
        UserModel userModel=new UserModel();
        userModel.newsNumber(MainActivity.this,userid);
    }




    @Override
    public void initView() {
        notification = (ImageView) findViewById(R.id.notification);
        id_addpost_img = (ImageView) findViewById(R.id.id_addpost_img);
        Img_user = (CircleImageView) findViewById(R.id.Img_user);
        alter = (ImageView) findViewById(R.id.alter);
        tv_bubble = (TextView) findViewById(R.id.tv_bubble);
        username = (TextView)findViewById(R.id.username);

        main_viewPager = (ViewPager) findViewById(R.id.id_content);
        id_tab_train = (LinearLayout) findViewById(R.id.id_tab_train);
        id_tab_club = (LinearLayout) findViewById(R.id.id_tab_club);
        id_tab_activity = (LinearLayout) findViewById(R.id.id_tab_activity);
        id_tab_post = (LinearLayout) findViewById(R.id.id_tab_post);

        mImgTrain = (ImageButton) findViewById(R.id.id_tab_train_img);
        mImgClub = (ImageButton) findViewById(R.id.id_tab_club_img);
        mImgChoicenessActivity = (ImageButton) findViewById(R.id.id_tab_activity_img);
        mImgPost = (ImageButton) findViewById(R.id.id_tab_post_img);

        tv01=(TextView)findViewById(R.id.tv_train);
        tv02=(TextView)findViewById(R.id.tv_tclub);
        tv03=(TextView)findViewById(R.id.tv_activity);
        tv04=(TextView)findViewById(R.id.tv_post);
        title =(TextView)findViewById(R.id.title);


        initDatas();//初始化数据

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);




        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //   userInfo();
    }

    @Override
    public void initEvent() {
        //对底部四个layout的监听
        id_tab_train.setOnClickListener(onClickListener);
        id_tab_club.setOnClickListener(onClickListener);
        id_tab_activity.setOnClickListener(onClickListener);
        id_tab_post.setOnClickListener(onClickListener);
        notification.setOnClickListener(onClickListener);
        id_addpost_img.setOnClickListener(onClickListener);
//        alter.setOnClickListener(onClickListener);

    }

    @Override
    public void setTitle() {

    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up buttom, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_tuisong) {
            intent.setClass(this,UserInformation.class);
            startActivity(intent);

        } else if (id == R.id.nav_clear) {
            //打开系统权限
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri1=Uri.parse("package:" + getPackageName());
            intent.setData(uri1);
            startActivity(intent);

        } else if (id == R.id.nav_yaoqing) {
            intent.setClass(this, AddPost.class);
            startActivity(intent);

        } else if (id == R.id.nav_help) {
            intent.setClass(this, MyAddress.class);
            startActivity(intent);

        } else if (id == R.id.nav_logout) {
//            SharedPreferences sharedPreferences;
//            SharedPreferences.Editor editor;
//            sharedPreferences = getSharedPreferences(FILENAME, MODE_PRIVATE);
//            editor = sharedPreferences.edit();
//            sharedPreferences.edit().clear().commit();
//            editor.commit();
            finish();

        }else if (id == R.id.alter){
            intent.setClass(MainActivity.this,UserInformation.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void initDatas() {

        fragmentList = new ArrayList<Fragment>();
        //将四个Fragment加入集合中
        fragmentList.add(new TrainFragment());
        fragmentList.add(new ClubFragment());
        fragmentList.add(new ChoicenessActivityFragment());
        fragmentList.add(new PostFragment());


        //初始化适配器
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return fragmentList.size();
            }

            @Override
            public Fragment getItem(int position) {
                // TODO Auto-generated method stub
                return fragmentList.get(position);
            }
        };






        //不要忘记设置ViewPager的适配器
        main_viewPager.setAdapter(mAdapter);
        //设置ViewPager的切换监听
        main_viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // TODO Auto-generated method stub
                main_viewPager.setCurrentItem(position);
                setImgAndText();
                selectTab(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

    }


    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            setImgAndText();
            switch (v.getId()) {
                case R.id.id_tab_train:
                    selectTab(0);
                    break;
                case R.id.id_tab_club:
                    selectTab(1);
                    break;
                case R.id.id_tab_activity:
                    selectTab(2);
                    break;
                case R.id.id_tab_post:
                    selectTab(3);
                    break;
                case R.id.notification:
                    intent.setClass(MainActivity.this,SystemNews.class);
                    startActivity(intent);
                    break;
                case R.id.id_addpost_img:
                    intent.setClass(MainActivity.this,AddPost.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.layout_open,R.anim.activity_disapear);
                    break;
                case R.id.alter:
                    intent.setClass(MainActivity.this,UserInformation.class);
                    startActivity(intent);
                default:
                    break;
            }
        }
    };


    //动态注册广播
    private void registerBroadCast(){
        IntentFilter intentFilter = new IntentFilter("refresh_user_news");
        myBroadCastReciver = new MyBroadCastReciver();
        registerReceiver(myBroadCastReciver,intentFilter);
    }
    //实现MyBroadCastReciver
    class MyBroadCastReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String news = bundle.getString("newsNum");
            if (news.equals(0)){
                tv_bubble.setVisibility(View.GONE);
            }else{
                tv_bubble.setText(news);
            }

        }
    }



    private void selectTab(int i) {
        //根据点击的Tab设置对应的ImageButton为绿色
        switch (i) {
            case 0:
                mImgTrain.setImageResource(R.drawable.ic_train_impress);
                tv01.setTextColor(this.getResources().getColor(R.color.green));
                title.setText("体育培训");
                break;
            case 1:
                mImgClub.setImageResource(R.drawable.ic_club_impress);
                tv02.setTextColor(this.getResources().getColor(R.color.green));
                title.setText("俱乐部");
                break;
            case 2:
                mImgChoicenessActivity.setImageResource(R.drawable.ic_activity_impress);
                tv03.setTextColor(this.getResources().getColor(R.color.green));
                title.setText("精品活动");
                break;
            case 3:
                mImgPost.setImageResource(R.drawable.ic_post_impress);
                tv04.setTextColor(this.getResources().getColor(R.color.green));
                title.setText("疯狂转帖");
                break;

        }
        //设置当前点击的Tab所对应的页面
        main_viewPager.setCurrentItem(i);
    }

    private void setImgAndText()
    {


        mImgTrain.setImageResource(R.drawable.ic_train_normol);
        mImgClub.setImageResource(R.drawable.ic_club_normol);
        mImgChoicenessActivity.setImageResource(R.drawable.ic_activity_normol);
        mImgPost.setImageResource(R.drawable.ic_post_normol);







        tv01.setTextColor(this.getResources().getColor(R.color.white));
        tv02.setTextColor(this.getResources().getColor(R.color.white));
        tv03.setTextColor(this.getResources().getColor(R.color.white));
        tv04.setTextColor(this.getResources().getColor(R.color.white));

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {  //按两次返回键退出
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void startService(){
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        android.os.Process.killProcess(android.os.Process.myPid());
        unregisterReceiver(myBroadCastReciver);
        super.onDestroy();
    }


    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    protected void onResume() {

        UserModel userModel=new UserModel();
        userModel.newsNumber(MainActivity.this,userid);
        super.onResume();

    }



    private int  getUserid(){
        int newsNumber;
        SharedPreferences sharedPreferences = getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
        newsNumber = sharedPreferences.getInt("userId",0);
        return newsNumber;
    }

    @Override
    public void onSuccess(user user) {
        if(user!=null){

            newsBubbleNumber = user.getNewsBubbleNumber();
            if( newsBubbleNumber.equals("0") ){ //设置消息数字为零不可见
                tv_bubble.setVisibility(View.GONE); //设置不可见并不占用空间
            }else{
                tv_bubble.setText(newsBubbleNumber);
            }

        }else{
            tv_bubble.setText(newsBubbleNumber);
        }

    }



    @Override
    public void onFailure() {
        tv_bubble.setVisibility(View.GONE); //设置不可见并不占用空间
    }



    private void userInfo(){
        Retrofit retrofit=new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(URL)
                .build();
        service service=retrofit.create(service.class);
        Call<UserInfo> call=service.userInf(userid);
        //3
        call.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> arg0, Response<UserInfo> arg1) {
                // TODO Auto-generated method stub
                username.setText(arg1.body().getUser_username());
                if (arg1.body().getUser_picture()!=null){
                    Picasso.with(MainActivity.this).load(IMG_URL+arg1.body().getUser_picture()).into(Img_user);
                }

            }

            @Override
            public void onFailure(Call<UserInfo> arg0, Throwable arg1) {
                // TODO Auto-generated method stub
                //Toast

            }
        });
    }

}
